<?php

namespace App\Kuafu\Guanyuan\Command;

use App\Kuafu\Base\Command\Traits\KfGetTimeInterval;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use App\Kuafu\CouponPackage\Model\CouponPackageOrderModel;
use App\Kuafu\Guanyuan\Enum\DishDetailEnum;
use App\Kuafu\Guanyuan\Model\DishDetailCHModel;
use App\Kuafu\Guanyuan\Model\DishDetailModel;
use App\Kuafu\Shop\Model\Shop;
use App\Library\FeiShu\SendFs;
use App\Library\SnowFlake\SnowFlake;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class PackageCouponDishDetailCommand extends Command
{
    use KfGetTimeInterval;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'guanyuan:packageCouponSyncDishDetail {--d=false :  是否直接执行 示例.true - 默认执行前一天数据 false - 交互式执行}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '观远券包同步:券包 购买数据';

    /**
     * Execute the console command
     */
    public function handle()
    {       // qa 环境关闭运行
        if (isTest()) {
            return false;
        }
        list($startTimeAt, $endTimeAt) = $this->getTimeInterval();

        $this->info('**************** 开始执行脚本 ****************');
        $inShopList           = Shop::getUsefulShopLists()->pluck('name', 'id')->toArray();
        $systemStartTimeConst = time();

        // 获取所有店铺信息
        $shopList = Shop::query()
                        ->get()
                        ->keyBy('id')
                        ->each(function ($item) {
                            // 处理省市区
                            $ssq = explode('-', $item['addressPrefix']);
                            if (empty($ssq)
                                || empty($ssq[0])
                                || empty($ssq[1])
                                || empty($ssq[2])
                            ) {
                                return;
                            }
                            $item['province'] = $ssq[0];
                            $item['city']     = $ssq[1];
                            $item['district'] = $ssq[2];

                        })
                        ->toArray();

        $queryDate = [];
        $diff      = ($endTimeAt - $startTimeAt) / 86400;

        for ($d = 1; $d <= $diff; $d++) {
            $queryDate[] = [
                'startTime' => $startTimeAt + 86400 * ($d - 1),
                'endTime'   => $startTimeAt + 86400 * $d
            ];
        }

        foreach ($queryDate as $date) {
            foreach ($inShopList as $shopId => $shopName) {
                // 删除库里对应的数据
                DishDetailModel::query()
                               ->where('checkoutTime', '>=', date('Y-m-d H:i:s', $date['startTime']))
                               ->where('checkoutTime', '<=', date('Y-m-d H:i:s', $date['endTime']))
                               ->where("poiName", "like",
                                   CommonService::zeroFill($shopList[$shopId]['shopCode']) . "%")
                               ->where('source', '=', DishDetailEnum::SOURCE_PACKAGE)
                               ->delete();

                try {
                    DishDetailCHModel::query()
                                     ->where('checkoutTime', '>=', date('Y-m-d H:i:s', $date['startTime']))
                                     ->where('checkoutTime', '<=', date('Y-m-d H:i:s', $date['endTime']))
                                     ->where('source', '=', DishDetailEnum::SOURCE_PACKAGE)
                                     ->where("poiName", 'LIKE',
                                         CommonService::zeroFill($shopList[$shopId]['shopCode']) . "%")
                                     ->delete();

                } catch (\Exception $exception) {
                    self::sendFs('Clickhouse 删除历史数据异常', ['3fgc8798']);
                }


                $couponPackageList = CouponPackageOrderModel::query()
                                                            ->where('createdAt', '>', $date['startTime'])
                                                            ->where('createdAt', '<', $date['endTime'])
                                                            ->where('shopId', $shopId)
                                                            ->where('payStatus', '=',
                                                                CouponPackageOrderModel::PAY_STATUS_1)
                                                            ->get();
                $insertData        = [];
                foreach ($couponPackageList as $detail) {
                    $createdAt    = $detail['createdAt']->format('Y-m-d H:i:s');
                    $insert       = [
                        'province'       => $shopList[$detail['shopId']]['province'],
                        'city'           => $shopList[$detail['shopId']]['city'],
                        'district'       => $shopList[$detail['shopId']]['district'],
                        'poiName'        => CommonService::zeroFill($shopList[$shopId]['shopCode']) . $shopList[$shopId]['name'],
                        'spuId'          => '',
                        'spuName'        => '',
                        'specs'          => '',
                        'unit'           => '',
                        'firstCateName'  => '',
                        'orderNo'        => $detail['orderId'],
                        'orderId'        => $detail['orderId'],
                        'count'          => 1,
                        'totalPrice'     => $detail['payPrice'] / 100,
                        'discountAmount' => 0,
                        'taxExcludedAmt' => $detail['payPrice'] / 100,
                        'goodsTime'      => $createdAt,
                        'orderTime'      => $createdAt,
                        'checkoutTime'   => $createdAt,
                        'categoryName'   => '',
                        'sourceName'     => DishDetailEnum::CODE_TEXT[DishDetailEnum::SOURCE_PACKAGE],
                        'orderPrice'     => $detail['payPrice'] / 100, //订单原价
                        'orderDiscount'  => 0, //订单优惠
                        'orderIncome'    => $detail['payPrice'] / 100, // 订单实收
                        'flagName'       => '',
                        'createdAt'      => date('Y-m-d H:i:s'),
                        'updatedAt'      => date('Y-m-d H:i:s'),
                        'discountName'   => DishDetailEnum::CODE_TEXT[DishDetailEnum::SOURCE_PACKAGE],
                        'source'         => DishDetailEnum::SOURCE_PACKAGE,
                        'dataFrom'       => 'kuafu',
                    ];
                    $insertData[] = $insert;
                }

                collect($insertData)->chunk(300)->each(function ($item) {
                    try {
                        $insertData = $item->toArray();
                        foreach ($insertData as &$datum) {
                            $datum['id'] = SnowFlake::nextIdCache();
                        }
                        $insertData = array_values($insertData);
                        DishDetailModel::query()->insert($insertData);
                        DishDetailCHModel::query()->insert($insertData);
                    } catch (\Exception $exception) {
                        self::sendFs('券包 Clickhouse 写入数据异常' . $exception->getMessage(), ['3fgc8798']);
                    }
                });
            }
        }

        $diffTime = time() - $systemStartTimeConst;
        $content  = date('Y-m-d H:i:s',
                $startTimeAt) . ' 至 ' . date('Y-m-d H:i:s',
                $endTimeAt) . ' 券包数据已经入库至观远, 耗时' . $diffTime . '秒';

        $shopList = '';
        foreach ($inShopList as $shopId => $shopName) {
            $shopList .= "\r\nid-" . $shopId . '|' . $shopName;
        }

        $content .= "\r\n涉及的门店有" . trim($shopList, ',');
        SendFs::newRobot(SendFs::ROBOT_GUANYUAN)->setTitleContent('夸父-券包数据 ' . date('Y-m-d H:i:s', time()),
            $content)
              ->send();
    }


    private static function sendFs($content, $fsUid = [])
    {
        if (!empty($content)) {
            SendFs::newRobot(SendFs::ROBOT_GUANYUAN)
                  ->setTitleContent('[券包] ' . date('Y-m-d H:i:s', time()), $content)
                  ->setAtUids($fsUid)
                  ->send();
        }
    }
}
